// pages/login/login.js
import authService from "../../services/auth.service";
import personalCenterService from "../../services/personal-center.service";
import {
  WX_STORAGE_KEY_TOKEN,
  WX_STORAGE_KEY_USER_PROFILE,
  WX_STORAGE_KEY_REMEMBER_ME
} from "../../utils/constants";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    username: "",
    password: "",
    verifyCode: "",
    verifyCodeKey: "",
    rememberMe: false,
    verifyCodeUrl: "",
  },

  updateVerifyCode: async function () {
    try {
      const res = await authService.getVerifyCode();
      this.setData({
        verifyCodeUrl: `${res.data.data?.image}`,
        verifyCodeKey: res.data.data?.key,
      });
    } catch (err) {
      wx.showToast({
        title: err.data && err.data.message || err.errMsg,
        icon: 'error'
      });
      throw err;
    }
  },

  forgetPassword: async function () {
    wx.navigateTo({
      url: `/pages/forget-password/forget-password?${this.data.username ? "username="+this.data.username : ''}`,
    })
  },

  login: async function () {
    try {
      if (this.data.username == null || this.data.username == "") {
        wx.showToast({
          title: '请输入用户名',
          icon: "error"
        });
        return;
      }
      if (this.data.password == null || this.data.password == "") {
        wx.showToast({
          title: '请输入密码',
          icon: "error"
        });
        return;
      }
      if (this.data.verifyCode == null || this.data.verifyCode == "") {
        wx.showToast({
          title: '请输入验证码',
          icon: "error"
        });
        return;
      }
      const res = await authService.login({
        username: this.data.username,
        password: this.data.password,
        verifyCodeKey: this.data.verifyCodeKey,
        verifyCode: this.data.verifyCode,
      });
      const authData = res.data.data;
      if (authData && authData.token) {
        const {
          token
        } = authData;
        wx.setStorageSync(WX_STORAGE_KEY_TOKEN, token);

        const userProfile = await personalCenterService.retrieve();
        wx.setStorageSync(WX_STORAGE_KEY_USER_PROFILE, userProfile);

        if (this.data.rememberMe) {
          wx.setStorageSync(WX_STORAGE_KEY_REMEMBER_ME, {
            username: this.data.username,
            password: this.data.password,
          });
        } else {
          wx.removeStorageSync(WX_STORAGE_KEY_REMEMBER_ME);
        }

        wx.showToast({
          title: '登录成功',
          icon: "success"
        });
        wx.navigateTo({
          url: '/pages/home/home',
        });
      }

    } catch (err) {
      wx.showToast({
        title: err.data && err.data.message || err.errMsg,
        icon: 'error'
      });
      this.updateVerifyCode();
      throw err;
    } finally {}
  },

  register: async function () {
    wx.navigateTo({
      url: '/pages/register/register',
    })
  },

  rememberMeChanged(event) {
    this.setData({
      rememberMe: event.detail,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const remember = wx.getStorageSync(WX_STORAGE_KEY_REMEMBER_ME);
    if (remember) {
      this.setData({
        username: remember.username,
        password: remember.password,
      });
    }
    this.updateVerifyCode();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})